package com.cakebackoffice.clientsoap.contract;


import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;

public class SoapArray<E> extends ArrayList<E> implements KvmSerializable {

    private String name;

    public SoapArray(String name) {
        this.name = name;
    }

    public SoapArray(int capacity, String name) {
        super(capacity);
        this.name = name;
    }

    public SoapArray(Collection<? extends E> es, String name) {
        super(es);
        this.name = name;
    }

    public PropertyInfo toPropertyInfo() {
        PropertyInfo value = new PropertyInfo();
        value.setName(this.getClass().getName());
        value.setType(this.getClass());
        value.setValue(this);
        return value;
    }

    public PropertyInfo toPropertyInfo(String name) {
        PropertyInfo value = new PropertyInfo();
        value.setName(name);
        value.setType(this.getClass());
        value.setValue(this);
        return value;
    }

    @Override
    public Object getProperty(int i) {
        Object o = this.get(i);
        if (o instanceof ContractObject) {
            return ((ContractObject) o).toPropertyInfo();
        }
        return o;
    }

    @Override
    public int getPropertyCount() {
        return this.size();
    }

    @Override
    public void setProperty(int i, Object o) {
        this.add(i, (E) o);
    }

    @Override
    public void getPropertyInfo(int i, Hashtable hashtable, PropertyInfo propertyInfo) {
        propertyInfo.name = this.getName();
        propertyInfo.type = this.getClass();
    }

    public String getName() {
        return name;
    }

    public SoapObject toSoapObject(String namespace, String name) {
        SoapObject result = new SoapObject(namespace, name);
        for (E elem : this) {
            if (elem instanceof ContractObject) {
                result.addSoapObject(((ContractObject) elem).toSoapObject(namespace, elem.getClass().getName()));
            } else {
                result.addProperty(elem.getClass().getName(), elem.toString());
            }
        }
        return result;
    }
}
